package com.mjf.stack;

import java.util.Scanner;

/**
 * 使用数组模拟栈
 */
public class ArrayStackDemo {

    public static void main(String[] args) {

        // 测试ArrayStack是否正确
        ArrayStack stack = new ArrayStack(5);
        String key = "";
        boolean loop = true;    // 控制是否退出菜单
        Scanner scanner = new Scanner(System.in);

        while (loop) {
            System.out.println("================================");
            System.out.println("show：显示栈");
            System.out.println("exit：退出程序");
            System.out.println("push：添加数据到栈(入栈)");
            System.out.println("pop：从栈取出数据(出栈)");
            System.out.println();

            key = scanner.next(); // 接收用户输入
            switch (key) {
                case "show":
                    stack.list();
                    break;

                case "push":
                    System.out.println("输入一个数：");
                    int value = scanner.nextInt();
                    stack.push(value);
                    break;

                case "pop":
                    try {
                        int result = stack.pop();
                        System.out.printf("取出的数据是%d\n", result);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;

                case "exit":
                    scanner.close();
                    loop = false;
                    break;

                default:
                    break;
            }
        }

    }

}


/**
 * 使用数组实现Stack
 */
class ArrayStack {

    /**
     * 栈的大小
     */
    private final int maxSize;
    private final int[] stack;
    /**
     * 表示栈顶，初始化为-1
     */
    private int top = -1;

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];  // 初始化
    }

    // 栈满
    public boolean isFull() {
        return top == maxSize - 1;
    }

    // 栈空
    public boolean isEmpty() {
        return top == -1;
    }

    // 入栈
    public void push(int value) {
        // 先判断是否栈满
        if (isFull()) {
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top] = value;
    }

    // 出栈:将栈顶的数据返回
    public int pop() {
        // 先判断是否栈空
        if (isEmpty()) {
            throw new RuntimeException("栈空");
        }

        int value = stack[top];
        top--;
        return value;
    }

    /**
     * 返回栈顶数据（没有出栈）
     */
    public int peek() {
        // 先判断是否栈空
        if (isEmpty()) {
            throw new RuntimeException("栈空");
        }
        return stack[top];
    }

    // 遍历栈，遍历时需要从栈顶开始显示数据
    public void list() {
        if (isEmpty()) {
            System.out.println("栈空，没有数据");
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n", i, stack[i]);
        }
    }

}